package cn.edu.swu.cart;

import cn.edu.swu.book.Book;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/cart")
public class CartAddServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(true);
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 或者返回适当的错误信息
            return;
        }

        String productIdStr = request.getParameter("productId");
        System.out.println("Received productId: " + productIdStr); // 调试输出
        if (productIdStr == null || productIdStr.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        int productId = Integer.parseInt(productIdStr);
//        int productId = Integer.parseInt(request.getParameter("productId"));
        session.setAttribute("productId", productId); // 存储 productId 到 session

        CartDAO cartDAO = new CartDAO();
        Book book = cartDAO.getBookById(productId);
        String name = book.getName();
        String image = book.getImage();
        double price = book.getPrice();
        String quantityStr = request.getParameter("quantity");
        int quantity = (quantityStr != null) ? Integer.parseInt(quantityStr) : 1; // 默认数量为1
        session.setAttribute("productId", productId); // 存储 productId 到 session
        boolean success = cartDAO.addToCart(userId, productId, name, image, price, quantity);
//        response.sendRedirect("./cart.html"); // 重定向到购物车页面
        List<Cart> items = cartDAO.getCartItems(userId);

        // 发送json响应
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
//        out.print("{\"success\":" + success + "}");
        buildJsonResponse(items, out, success);
        out.close();
    }

//    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        HttpSession session = request.getSession(true);
//        Integer userId = (Integer) session.getAttribute("userId");
//        if (userId == null) {
//            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//            response.getWriter().println("User is not logged in.");
//            return;
//        }
//
//        String productIdStr = request.getParameter("productId");
//        if (productIdStr == null || productIdStr.isEmpty()) {
//            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
//            response.getWriter().println("Product ID is required.");
//            return;
//        }
//        int productId = Integer.parseInt(productIdStr);
//
//        // 存储 productId 到 session
//        session.setAttribute("productId", productId);
//
//        // 调用 DAO 添加到购物车逻辑
//        CartDAO cartDAO = new CartDAO();
//        Book book = cartDAO.getBookById(productId);
//        String name = book.getName();
//        String image = book.getImage();
//        double price = book.getPrice();
//        String quantityStr = request.getParameter("quantity");
//        int quantity = (quantityStr != null) ? Integer.parseInt(quantityStr) : 1; // 默认数量为1
//        boolean success = cartDAO.addToCart(userId, productId, name, image, price, quantity);
//
//        // 重定向到购物车页面或其他逻辑
////        response.sendRedirect("./cart.html");
////        System.out.println("Redirecting to: ./cart.html");
//    }

//    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        HttpSession session = request.getSession(false);
//        Integer userId = (Integer) session.getAttribute("userId");
//        if (userId == null) {
//            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//            response.getWriter().println("No active session found. Please login.");
//            return;
//        }
//        Integer productId = (Integer) session.getAttribute("productId");
//        System.out.println("Received productId: " + productId); // 调试输出
//        if (productId == null) {
//            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
//            response.getWriter().println("Product ID is missing in session.");
//            return;
//        }
//
//        CartDAO cartDAO = new CartDAO();
//        List<Cart> items = cartDAO.getCartItems(userId);
////        session.setAttribute("items", items); // 存储购物车项列表到会话中
//
//        response.setContentType("application/json");
//        PrintWriter out = response.getWriter();
//        buildJsonResponse(items, out, true);
//        out.close();
//    }

    private void buildJsonResponse(List<Cart> items, PrintWriter out, boolean success) {
        out.print("{\"success\":" + success + ", \"items\":[");
        for (int i = 0; i < items.size(); i++) {
            Cart item = items.get(i);
            out.print("{"
                    + "\"id\": " + item.getId() + ", "
                    + "\"name\": \"" + item.getName() + "\", "
                    + "\"image\": \"" + item.getImage() + "\", "
                    + "\"quantity\": " + item.getQuantity() + ", "
                    + "\"price\": " + item.getPrice() + "}");
            if (i < items.size() - 1) {
                out.print(", ");
            }
            out.print("}");
        }
        out.print("]");
    }
}